package com.ybkj.daijia.server.event.listener;

import com.ybkj.daijia.PushDataV4;
import com.ybkj.daijia.Setting;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.api.gexin.GeTuiEmployV4;
import com.ybkj.daijia.api.jpush.JiGuangEmployV4;
import com.ybkj.daijia.server.event.model.AnnouncementEvent;
import com.ybkj.daijia.server.model.Announcement;
import com.ybkj.daijia.server.model.Driver;
import com.ybkj.daijia.server.service.DriverService;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
public class AnnouncementEventListener implements ApplicationListener<AnnouncementEvent> {

    private static final Logger logger = LoggerFactory.getLogger(AnnouncementEventListener.class);

    @Autowired
    private DriverService driverService;
    @Autowired
    private SettingUtils settingUtils;


    @Override
    @Async
    public void onApplicationEvent(AnnouncementEvent event) {

        logger.debug("AnnouncementEvent event:{}", event);

        Announcement announcement = (Announcement) event.getSource();
        List<Driver> drivers = event.getDrivers();

        Setting setting = settingUtils.get();

        Integer time = 0;
        for (Driver driver : drivers) {

            try {

                String text = announcement.getTitle();
                if (text.length() > 220) {
                    text = text.substring(0, 220);
                }

                //发送设备推送
                ++time;
                PushDataV4 pushDataV4 = new PushDataV4();
                pushDataV4.setCode("0X00");
                pushDataV4.setData(announcement.getId());
                Map<String, String> extra = new HashMap<String, String>();
                extra.put("content", text);
                pushDataV4.setExtra(extra);
                pushDataV4.setType("0X03");

                boolean getuiOnline = false;
                if (StringUtils.isNotBlank(driver.getUserID())) {
                    getuiOnline = GeTuiEmployV4
                        .getClientOnline(driver.getUserID(), settingUtils.get());
                }

                if (getuiOnline) {
                    GeTuiEmployV4.push(driver, pushDataV4, setting);
                } else {
                    if (StringUtils.isNotBlank(driver.getRegistrationId())) {
                        JiGuangEmployV4.push(driver, pushDataV4, setting);
                    }
                }

            } catch (IOException e) {
                logger.debug("push error : " + e.getMessage());
            }
        }
    }
}
